/**
 * @Title: OnstarApplication.java
 * @author 7828wc
 * @date 2015年7月28日 下午4:03:32
 */
package com.shanghaionstar;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.view.View;

import com.midea.iot.sdk.cloud.openapi.MSmartSDK;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.common.IServerUrls;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.mvp.base.core.NetworkUtil;
import com.onstar.cn.framework.network.BaseRequest;
import com.onstar.cn.framework.utils.ContextInstance;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.more.response.HeadImgRes;
import com.onstar.cn.more.response.VehicleImgRes;
import com.onstar.cn.sqlite.xutil.DbUtils;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.activity.NoNetActivity;
import com.shanghaionstar.retrofit.RxRetrofitApp;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.CrashHandler;
import com.shanghaionstar.utils.DevelopServerEnvironmentUtil;
import com.shanghaionstar.utils.MyActivityManager;

import java.util.List;

import rx.functions.Action1;

/**
 * @author 7828wc
 * @ClassName: OnstarApplication
 * @Description: Application 处理Activity间共享数据
 * @date 2015年7月28日 下午4:03:32
 */
public class OnstarApplication extends Application {
    private static OnstarApplication application;

    private HeadImgRes headImgRes;
    private VehicleImgRes res;
    private boolean isMroForeground = false;
    //
    private List<ResponBannerEntity> bannerEntities;

    public int getmLoginState() {
        return mLoginState;
    }

    public void setmLoginState(int mLoginState) {
        this.mLoginState = mLoginState;
    }

    private int mLoginState;

    private String brocastCount = "";

    private long brocastId;

    public HeadImgRes getHeadImgRes() {
        return headImgRes;
    }

    public void setHeadImgRes(HeadImgRes headImgRes) {
        this.headImgRes = headImgRes;
    }

    public VehicleImgRes getRes() {
        return res;
    }

    public void setRes(VehicleImgRes res) {
        this.res = res;
    }

    public static OnstarApplication getApplication() {
        return application;
    }

    public static void setApplication(OnstarApplication application) {
        OnstarApplication.application = application;
    }


    public long getBrocastId() {
        return brocastId;
    }

    //
    public void setBrocastId(long brocastId) {
        this.brocastId = brocastId;
    }

    public String getBrocastCount() {
        return brocastCount;
    }

    public void setBrocastCount(String brocastCount) {
        this.brocastCount = brocastCount;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        BusinessUtil.refreshPolling(this);
        BusinessUtil.clearOnstarAppContext(this);
        DevelopServerEnvironmentUtil.getInstance().setEnvironmentMode(IServerUrls.envMode, this);
        MultiDex.install(getApplicationContext());
//        LeakCanary.install(this);
//        BlockCanary.install(this, new AppBlockCanaryContext()).start();
        ContextInstance.getInstance().setAppContext(this);
        MSmartSDK.getInstance().initSDKWithAppID(this.getApplicationContext(), "1040", "364ab7012fcd85d086b52936d3a62976", "40 ");
        setApplication(this);
        try {
            // 初始化图片加载
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                    .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                    .discCacheFileNameGenerator(new Md5FileNameGenerator()).discCacheFileCount(100)
                    .tasksProcessingOrder(QueueProcessingType.LIFO)
                    .memoryCache(new WeakMemoryCache())
                    .memoryCacheSize(2 * 1024 * 1024)
                    .discCacheSize(50 * 1024 * 1024)
                    .threadPoolSize(5)
                    .build();
            ImageLoader.getInstance().init(config);
        } catch (Exception e) {
            e.printStackTrace();
        }

        CrashHandler crashHandler = new CrashHandler(getApplicationContext());
        crashHandler.setLietener(new CrashHandler.CarshHandlerListener() {
            @Override
            public void result() {
//                if (!Boolean.valueOf(IServerUrls.isDevelopMode)) {
//                    Runtime.getRuntime().exit(0);
//                    android.os.Process.killProcess(android.os.Process.myPid());
//                }
            }
        });
        activityMonitor();
        // CrashHandler crashHandler = new
        // CrashHandler(getApplicationContext());
        // crashHandler.setLietener(new CarshHandlerListener() {
        // @Override
        // public void result() {
        // Runtime.getRuntime().exit(0);
        // android.os.Process.killProcess(android.os.Process.myPid());
        // }
        // });
        //
        // SettingUtil.checkNewFunctionUnread(this);
        registerNetConnect();

        mDbUtils = DbUtils.create(this, "onstar.db", 1, new DbUtils.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbUtils db, int oldVersion, int newVersion) {
//               db.dropDb();
            }
        });
        mDbUtils = mDbUtils.configAllowTransaction(true);

        RxRetrofitApp.init(this,true);
    }

    public static DbUtils getmDbUtils() {
        return mDbUtils;
    }


    private static DbUtils mDbUtils;

    private void registerNetConnect() {
        RxBus.getDefault()
                .toObserverable(BaseRequest.CHECK_NET_CONNECT, String.class)
                .subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (!NetworkUtil.isConnect(getApplication()) && !NetworkUtil.isApplicationBroughtToBackground(getApplication())) {
                            final ToastView toastView = new ToastView(getApplication());
                            toastView.showNetToastWithClickListen(R.string.no_net_connected, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent it = new Intent(getApplication(), NoNetActivity.class);
                                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getApplication().startActivity(it);
                                    toastView.cancel();
                                }
                            });
                        }
                    }
                });
    }

    private int activityCount = 0;

    public boolean isActivityFront() {
        return activityCount > 0;
    }

    public int getActivityFrontCount() {
        return activityCount;
    }

    private void activityMonitor() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                activityCount++;
                LogManager.getInstance().d("" + activityCount);
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                activityCount--;
                LogManager.getInstance().d("" + activityCount);
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }


    public static DisplayImageOptions getOptions(boolean cacheOnDisc, int resId) {
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(resId).showImageForEmptyUri(resId)
                .showImageOnFail(resId).resetViewBeforeLoading(false).cacheOnDisc(cacheOnDisc).cacheInMemory(true)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED).bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(200)).build();
        return options;
    }

    public static DisplayImageOptions getOptions(int resId) {
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(resId).showImageForEmptyUri(resId)
                .showImageOnFail(resId).resetViewBeforeLoading(false).cacheOnDisc(true).cacheInMemory(false)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(200)).build();
        return options;
    }

    public static DisplayImageOptions getOptions(boolean cacheOnDisc, boolean cacheOnMemory, int resId) {
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(resId).showImageForEmptyUri(resId)
                .showImageOnFail(resId).resetViewBeforeLoading(false).cacheOnDisc(cacheOnDisc)
                .cacheInMemory(cacheOnMemory).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(200)).build();
        return options;
    }

//    public ServiceItem getItem() {
//        return item;
//    }
//
//    public void setItem(ServiceItem item) {
//        this.item = item;
//    }
//
//    private ServiceItem item, carAssessStatusItem;

//    public ServiceItem getCarAssessStatusItem() {
//        return carAssessStatusItem;
//    }
//
//    public void setCarAssessStatusItem(ServiceItem carAssessStatusItem) {
//        this.carAssessStatusItem = carAssessStatusItem;
//    }

    public boolean isMroForeground() {
        return isMroForeground;
    }

    public void setMroForeground(boolean mroForeground) {
        isMroForeground = mroForeground;
    }

    public List<ResponBannerEntity> getBannerEntities() {
        return bannerEntities;
    }

    public void setBannerEntities(List<ResponBannerEntity> bannerEntities) {
        this.bannerEntities = bannerEntities;
    }


}
